package com.desaysv.wandroid.fragment.main

import android.annotation.SuppressLint
import android.app.Activity.RESULT_OK
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.*
import android.widget.Toast
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.desaysv.mvp.MVPFragment
import com.desaysv.svnotice.MessageBlockQueue
import com.desaysv.svview.loading.LoadingDialog
import com.desaysv.wandroid.TestService
import com.desaysv.wandroid.adapter.AirticAdapter
import com.desaysv.wandroid.adapter.BannerAdapter
import com.desaysv.wandroid.adapter.MenuAdapter
import com.desaysv.wandroid.databinding.FragmentMainBinding
import com.desaysv.wandroid.entity.AirticEntity
import com.desaysv.wandroid.entity.BannerEntity
import com.desaysv.wandroid.fragment.main.mvp.MainContract
import com.desaysv.wandroid.fragment.main.mvp.MainModel
import com.desaysv.wandroid.fragment.main.mvp.MainPresenter
import com.desaysv.wandroid.ui.web.AirticWebActivity
import com.desaysv.wandroid.utils.UDPUtils
import com.youth.banner.indicator.CircleIndicator
import com.youth.banner.listener.OnBannerListener
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetAddress

/**
 * @author linzi
 * @date 2022-12-2 15:26
 * @context xczxc
 */
class MainFragment : MVPFragment<MainContract.IMainView, MainModel, MainPresenter>(),
    MainContract.IMainView {
    private val TAG = "MainFragment"
    private lateinit var mMainBinding: FragmentMainBinding
    private var mBannerInfo = ArrayList<BannerEntity>()
    private var mAirticsInfo = ArrayList<AirticEntity.DatasBean>()
    private var mTopAirticCount = 0
    private var currenPage = 0
    private var mAirticAdapter: AirticAdapter? = null

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mMainBinding = FragmentMainBinding.inflate(inflater)
        return mMainBinding.root
    }

    companion object {
        // TODO: Rename and change types and number of parameters
        /**
         * @author linzi
         * @date 2022-12-2 15:29
         * @context 创建单例对象
         */
        @JvmStatic
        fun newInstance() =
            MainFragment()
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        LoadingDialog.show(activity)
        mMainBinding.refresh.setOnRefreshListener {
            getPresenter()?.getBanner()
            currenPage = 0
//            getPresenter()?.getIndexData(currenPage)
            getPresenter()?.getTopAirtics()
            var intents=Intent()
            intents.setClass(requireActivity(),TestService::class.java)
            requireActivity().startService(intents)

//            tranTest()
//            service()
//            client()

        }
        mMainBinding.refresh.setOnLoadMoreListener {
            currenPage++
            getPresenter()?.getIndexData(currenPage)
            var intents=Intent()
            intents.setClass(requireActivity(),TestService::class.java)
            requireActivity().stopService(intents)
        }
        getPresenter()?.getBanner()
        getPresenter()?.getTopAirtics()
        initMenu()

        mMainBinding.rlText?.setOnClickListener {
            Toast.makeText(requireContext(), "123445", Toast.LENGTH_SHORT).show()
        }
        UDPUtils.startService()
    }

    override fun setPresenter(): MainPresenter {
        return MainPresenter()
    }

    override fun showBanner(banners: List<BannerEntity>?) {
        Log.e(TAG, "showBanner: " + banners?.size)
        mMainBinding.banner.apply {
            if (banners == null || banners.isEmpty()) {
                visibility = View.GONE
            } else {
                visibility = View.VISIBLE
            }
        }
        if (mMainBinding.banner.visibility == View.GONE) {
            return
        }
        mBannerInfo.clear()
        mBannerInfo.addAll(banners!!)
        val images = ArrayList<String>()
        mBannerInfo.forEach {
            images.add(it.imagePath)
        }
        mMainBinding.banner.apply {
            addBannerLifecycleObserver(activity)
            indicator = CircleIndicator(activity)
            isAutoLoop(true)

        }
    }

//    private fun tranTest(){
////        var ani=TranslateAnimation(0f,(mMainBinding.rlText.width.toFloat()-10)*-1,0f,0f)
////        ani.duration=500
////        ani.fillAfter=true
////        ani.setAnimationListener(object:Animation.AnimationListener{
////            override fun onAnimationStart(animation: Animation?) {
////                mMainBinding.rlText.visibility=View.VISIBLE
////            }
////
////            override fun onAnimationEnd(animation: Animation?) {
////            }
////
////            override fun onAnimationRepeat(animation: Animation?) {
////            }
////
////        })
////        mMainBinding.rlText.startAnimation(ani)
//
//        var anim=ObjectAnimator.ofFloat(mMainBinding.rlText,"translationX",0f,(mMainBinding.rlText.width.toFloat()-10)*-1)
//        anim.setDuration(500)
//        anim.start()
//    }

    @SuppressLint("NotifyDataSetChanged")
    override fun refreshData(airticEntity: AirticEntity?) {
        LoadingDialog.hideLoading()
        if (mMainBinding.refresh.isRefreshing) {
            mMainBinding.refresh.finishRefresh()
        }
        if (mMainBinding.refresh.isLoading) {
            mMainBinding.refresh.finishLoadMore()
        }
        if (airticEntity == null || airticEntity.datas.size == 0) {
            if (currenPage > 0) {
                currenPage--
            }
            return
        }
        if (currenPage == 0) {
            mAirticsInfo.clear()
        }
        mAirticsInfo.addAll(airticEntity.datas)
        if (mAirticAdapter == null) {
            mAirticAdapter = AirticAdapter(mAirticsInfo, activity)
            mAirticAdapter?.setRootClick(true)
            mAirticAdapter?.setOnItemClickListener { v, position ->
                Log.e(TAG, "refreshData:====>$position")
                val intent = Intent(activity, AirticWebActivity::class.java)
                intent.putExtra(AirticWebActivity.PARAMS_URL, mAirticsInfo.get(position).link)
                intent.putExtra(AirticWebActivity.PARAMS_TITLE, mAirticsInfo.get(position).title)
                startActivityForResult(intent,10001)
            }
            val linearLayoutManager = object : LinearLayoutManager(activity) {
                override fun canScrollVertically(): Boolean {
                    return false
                }
            }
            mMainBinding.recycle.layoutManager = linearLayoutManager
            mMainBinding.recycle.adapter = mAirticAdapter
        }
        mAirticAdapter?.setTopAirticCount(mTopAirticCount)
        mAirticAdapter?.apply {
            notifyDataSetChanged()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode==10001&&resultCode== RESULT_OK){
            Toast.makeText(requireContext(),"11111111",Toast.LENGTH_SHORT).show()
        }
    }

    override fun refreshTopData(datas: List<AirticEntity.DatasBean>?) {
        mAirticsInfo.clear()
        if (datas != null) {
            mAirticsInfo.addAll(datas)
        }
        mTopAirticCount = mAirticsInfo.size
        getPresenter()?.getIndexData(currenPage)
    }

    override fun initMenu() {
        val menuAdapter = MenuAdapter(activity)
        menuAdapter.setRootClick(true)
        menuAdapter.setOnItemClickListener { v, position ->

        }
        val manager = object : GridLayoutManager(activity, 4) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        mMainBinding.menus.layoutManager = manager
        mMainBinding.menus.adapter = menuAdapter
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            mMainBinding.scroll.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
                if (scrollY <= 200) {
                    mMainBinding.edSearch.visibility = View.VISIBLE
                    mMainBinding.edSearch.alpha = ((200 - scrollY) / 2 / 100f)
                } else {
                    mMainBinding.edSearch.alpha = 1f
                    mMainBinding.edSearch.visibility = View.GONE
                }
            }
        }
        MessageBlockQueue.getInstance().addObserver(object : MessageBlockQueue.MessageObserverImpl(){
            override fun post(queueEvent: MessageBlockQueue.QueueEvent?) {
                queueEvent?.apply {
                    Log.e(TAG, "post: $event" )
                }
            }
        })

        MessageBlockQueue.getInstance().subscribe(String::class.java, ob)
        MessageBlockQueue.getInstance().subscribe(Int::class.java, object : MessageBlockQueue.MessageSubscribeImpl<Int>() {
            override fun post(queueEvent: Int?) {
                queueEvent?.apply {
                    Log.e(TAG, "post: subscribeInt===>$queueEvent")
                }
            }

        })
        MessageBlockQueue.getInstance().subscribe(TestService.Stub::class.java,processOb)
    }

    var ob=object : MessageBlockQueue.MessageSubscribeImpl<String>() {
        override fun post(queueEvent: String?) {
            queueEvent?.apply {
                Log.e(TAG, "post: subscribe===>$queueEvent")
            }
        }
    }
    val processOb=object : MessageBlockQueue.MessageSubscribeImpl<TestService.Stub>(){
        override fun post(queueEvent: TestService.Stub?) {
            Log.e(TAG, "post: process=====>${queueEvent?.status}")
        }

    }

    fun service(){
        Thread{
            val mSocket=DatagramSocket(9999)
            val data = ByteArray(1024)
            // 将字节数组和数组的长度传进DatagramPacket 创建的对象里面
            val pack = DatagramPacket(data, data.size)
            while (true){
                mSocket.receive(pack)
                var str=String(pack.data,0,pack.length)
                Log.e(TAG, "linzi_service: $str")
            }
        }.start()

    }

    fun client(){
        Thread{
            val mSocket=DatagramSocket(9998)
            for (x in 0..10){
                val data = "info:${x}".toByteArray()
                // 将字节数组和数组的长度传进DatagramPacket 创建的对象里面
                val pack = DatagramPacket(data, data.size, InetAddress.getByName("127.0.0.1"),9999)
                mSocket.send(pack)
                Log.e(TAG, "linzi_client: ${String(data)}")
            }
        }.start()
    }
}